package com.jhhc.EngineeringSafety.Calculate;

import com.alibaba.fastjson2.JSONObject;
import com.jhhc.EngineeringSafety.BaseInfo.entity.BDMS_ES_FORECASTOBJ_B;
import com.jhhc.EngineeringSafety.BaseInfo.entity.result.*;
import com.jhhc.EngineeringSafety.BaseInfo.service.BDMS_ES_FORECASTOBJ_BService;
import com.jhhc.EngineeringSafety.Calculate.Forecast.entity.BDMS_CALCULATESCHEME_M;
import com.jhhc.EngineeringSafety.Calculate.Forecast.entity.BDMS_YB_RESULT_M;
import com.jhhc.EngineeringSafety.Calculate.Forecast.entity.param.*;
import com.jhhc.EngineeringSafety.Calculate.Forecast.entity.result.*;
import com.jhhc.EngineeringSafety.Calculate.Forecast.service.BDMS_CALCULATESCHEME_M33Service;
import com.jhhc.EngineeringSafety.Calculate.Forecast.service.BDMS_YB_RESULT_M3Service;
import com.jhhc.utils.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

@Api(value = "EngineeringSafetyCalculateController", tags = {"预报计算服务"})
@RequestMapping(value = {"EngineeringSafety/Calculate/Forecast"}, headers = {"Accept=application/json"})
@RestController("EngineeringSafetyCalculateController")
public class CalculateController {
    @Autowired
    private BDMS_CALCULATESCHEME_M33Service bdms_calculatescheme_mService;

    @Autowired
    private BDMS_ES_FORECASTOBJ_BService bdms_es_forecastobj_bService;

    @Autowired
    private BDMS_YB_RESULT_M3Service bdms_yb_result_m3Service;

    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    Calendar calendar = new GregorianCalendar();
    DecimalFormat decimalFormat = new DecimalFormat("#.#####");


    //获取最新的计算方案信息
    @ApiOperation("获取最新的计算方案信息")
    @RequestMapping(value = "GetNewCalSchemeInfo", headers = "Accept=application/json", method = RequestMethod.POST)
    public JsonResult getNewCalSchemeInfo(@RequestBody CalSchemeParam param) {

        return    bdms_calculatescheme_mService.selectOne(param);
    }


    //设置监测点位实测数据
    @ApiOperation("设置监测点位实测数据")
    @RequestMapping(value = {"SetMonitoringData"}, headers = {"Accept=application/json"}, method = {RequestMethod.POST})
    public JsonResult setMonitoringData(@RequestBody DataParam dataParam) throws ParseException {
        JsonResult jsonResult = new JsonResult();
        int  a=0;


       List<BDMS_ES_FORECASTOBJ_B> bdms_es_forecastobj_bs = bdms_es_forecastobj_bService.QmonitoringPonit(dataParam.getProjectId(),dataParam.getEngineeringId(), dataParam.getMonitoringSubjectId(), dataParam.getElementId());

       if (bdms_es_forecastobj_bs.size()>0){
           for (BDMS_ES_FORECASTOBJ_B bdms_es_forecastobj_b : bdms_es_forecastobj_bs) {
              String id = bdms_es_forecastobj_b.getMonitorid();
               if (dataParam.getDatas().size()>0) {
                   Datas data = dataParam.getDatas().stream().filter(datas -> datas.getMonitorId().equals(id)).findAny().orElse(null);
                   if (data != null) {
                       String monId = data.getMonitorId();
                       String value = data.getValue();
                       int res = bdms_es_forecastobj_bService.update(value, monId);
                       a += res;
                   }
               }else {
                   jsonResult.setSucceeded(true);
                   jsonResult.setStatusCode(200);
                   jsonResult.setRemark("请输入对应监测点位数据信息");
                   return jsonResult;
               }
           }
           if (a==0){
               jsonResult.setSucceeded(true);
               jsonResult.setStatusCode(200);
               jsonResult.setRemark("监测点位信息不匹配，请检查后重新输入");
               return jsonResult;
           }else {
               jsonResult.setData("设置成功条数为："+a);
               jsonResult.setSucceeded(true);
               jsonResult.setStatusCode(200);
               jsonResult.setRemark("请求成功");
               return jsonResult;
           }

       }else {
           jsonResult.setSucceeded(true);
           jsonResult.setStatusCode(200);
           jsonResult.setRemark("未查询到相关监测点位信息");
           return jsonResult;
       }
    }




    @ApiOperation("位移量模型计算")
    @RequestMapping(value = {"RunByDisplacement"}, headers = {"Accept=application/json"}, method = {RequestMethod.POST})
    public JsonResult runByDisplacement(@RequestBody RunYLParam runParam) throws ParseException {
        JsonResult jsonResult = new JsonResult();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dateTime1 = LocalDateTime.parse(runParam.getForecastBeginTime(), formatter);
        LocalDateTime dateTime2 = LocalDateTime.parse(runParam.getForecastTime(), formatter);
        if (dateTime1.compareTo(dateTime2) <= 0) {
            RunResult result = new RunResult();
            BDMS_CALCULATESCHEME_M bdms_calculatescheme_m = new BDMS_CALCULATESCHEME_M();
            bdms_calculatescheme_m.setCschemeid(runParam.getCalSchemeId());
            bdms_calculatescheme_m.setCschemenm(runParam.getCalSchemeName());
            bdms_calculatescheme_m.setDtmforecast(runParam.getForecastTime());
            bdms_calculatescheme_m.setDtmstart(runParam.getForecastBeginTime());
            this.calendar.setTime(this.format.parse(runParam.getForecastTime()));
            this.calendar.add(Calendar.DATE, runParam.getForecastDays());
            bdms_calculatescheme_m.setDtmend(this.format.format(this.calendar.getTime()));
            bdms_calculatescheme_m.setFschemeid(String.valueOf(runParam.getElementId()));
            bdms_calculatescheme_m.setPid(runParam.getProjectId());
            bdms_calculatescheme_m.setDtmcalculate(this.format.format(new Date()));
            bdms_calculatescheme_m.setUserid(runParam.getUserId());
            BDMS_CALCULATESCHEME_M bdmsCalculateschemeM = bdms_calculatescheme_mService.seletcById(runParam.getProjectId(), runParam.getCalSchemeId());
            if (bdmsCalculateschemeM == null) {

                List<EngineeringResult> engineeringResults = new ArrayList<>();
                List<BDMS_ES_FORECASTOBJ_B> bdms_es_forecastobj_bs = bdms_es_forecastobj_bService.QmonitoringPonit(runParam.getProjectId()
                        , runParam.getEngineeringId(),runParam.getMonitoringSubjectId(),runParam.getElementId());
                if (bdms_es_forecastobj_bs.size()>0){
                    this.bdms_calculatescheme_mService.insert(bdms_calculatescheme_m);
                    CalSchemeInfo calSchemeInfo = new CalSchemeInfo();
                    calSchemeInfo.setCalSchemeId(bdms_calculatescheme_m.getCschemeid());
                    if (bdms_calculatescheme_m.getAliasnm() != null) {
                        calSchemeInfo.setCalSchemeName(bdms_calculatescheme_m.getAliasnm());
                    } else {
                        calSchemeInfo.setCalSchemeName(bdms_calculatescheme_m.getCschemenm());
                    }
                    calSchemeInfo.setForecastTime(bdms_calculatescheme_m.getDtmforecast().substring(0, 19));
                    calSchemeInfo.setOperateTime(bdms_calculatescheme_m.getDtmcalculate().substring(0, 19));
                    if (bdms_calculatescheme_m.getState() != null)
                        switch (bdms_calculatescheme_m.getState()) {
                            case 0:
                                calSchemeInfo.setStateInfo("新建方案");
                                break;
                            case 1:
                                calSchemeInfo.setStateInfo("计算中");
                                break;
                            case 2:
                                calSchemeInfo.setStateInfo("计算失败");
                                break;
                            case 3:
                                calSchemeInfo.setStateInfo("计算完成");
                                break;
                            default:
                                break;
                        }
                    calSchemeInfo.setState(bdms_calculatescheme_m.getState());
                    calSchemeInfo.setUserId(String.valueOf(bdms_calculatescheme_m.getUserid()));
                    calSchemeInfo.setForecastBeginTime(bdms_calculatescheme_m.getDtmstart().substring(0, 19));
                    calSchemeInfo.setForecastEndTime(bdms_calculatescheme_m.getDtmend().substring(0, 19));
                    //calSchemeInfo.setDescription(bdms_calculatescheme_m.getRemark());
                    result.setCalSchemeInfo(calSchemeInfo);
                    Date date1 = this.format.parse(bdms_calculatescheme_m.getDtmforecast());
                    Date date2 = this.format.parse(bdms_calculatescheme_m.getDtmend());
                    Date date3 = this.format.parse(bdms_calculatescheme_m.getDtmstart());
                    int hourF = Integer.parseInt(String.valueOf(((date2.getTime() - date1.getTime()) / 3600000L)/24));
                    int hourM = Integer.parseInt(String.valueOf(((date1.getTime() - date3.getTime()) / 3600000L)/24));
                    //根据工程分组
                    // 根据engid、objforecastid和monitortypeid属性进行多级分组
                    Map<String, Map<String, Map<String, List<BDMS_ES_FORECASTOBJ_B>>>> groupedData = bdms_es_forecastobj_bs.stream()
                            .collect(Collectors.groupingBy(BDMS_ES_FORECASTOBJ_B::getEngid,
                                    Collectors.groupingBy(BDMS_ES_FORECASTOBJ_B::getObjforecastid,
                                            Collectors.groupingBy(BDMS_ES_FORECASTOBJ_B::getMonitortypeid))));
                    // 打印每个分组的数据
                    for (Map.Entry<String, Map<String, Map<String, List<BDMS_ES_FORECASTOBJ_B>>>> engEntry : groupedData.entrySet()) {
                        String engid = engEntry.getKey();
                        EngineeringResult engineeringResult =new EngineeringResult();
                        List<MonitoringSubjectResult> monitoringSubjectResults = new ArrayList<>();
                        engineeringResult.setEngineeringId(engid);
                        Map<String, Map<String, List<BDMS_ES_FORECASTOBJ_B>>> objForecastMap = engEntry.getValue();
                        for (Map.Entry<String, Map<String, List<BDMS_ES_FORECASTOBJ_B>>> objForecastEntry : objForecastMap.entrySet()) {
                            String objforecastid = objForecastEntry.getKey();
                            MonitoringSubjectResult monitoringSubjectResult = new MonitoringSubjectResult();
                            monitoringSubjectResult.setMonitoringSubjectId(objforecastid);
                            List<MonitoringElementResult> monitoringElementResults = new ArrayList<>();
                            Map<String, List<BDMS_ES_FORECASTOBJ_B>> monitorTypeMap = objForecastEntry.getValue();
                            for (Map.Entry<String, List<BDMS_ES_FORECASTOBJ_B>> monitorTypeEntry : monitorTypeMap.entrySet()) {
                                MonitoringElementResult monitoringElementResult = new MonitoringElementResult();
                                List<MonitoringPointResult> monitoringPointResults = new ArrayList<>();
                                String monitortypeid = monitorTypeEntry.getKey();
                                monitoringElementResult.setElementId(monitortypeid);
                                List<BDMS_ES_FORECASTOBJ_B> group = monitorTypeEntry.getValue();
                                for (BDMS_ES_FORECASTOBJ_B bdms_es_forecastobj_b : group) {
                                    engineeringResult.setMainHeading(bdms_es_forecastobj_b.getEng()+bdms_es_forecastobj_b.getMonitortype()+"风险预报");
                                    engineeringResult.setSubHeading("作业预报根据时间："+runParam.getForecastBeginTime()+"--" +runParam.getForecastTime());
                                    engineeringResult.setEngineeringName(bdms_es_forecastobj_b.getEng());
                                    monitoringSubjectResult.setMonitoringSubjectName(bdms_es_forecastobj_b.getObjforecast());
                                    monitoringElementResult.setElementName(bdms_es_forecastobj_b.getMonitortype());
                                    MonitoringPointResult monitoringPointResult = new MonitoringPointResult();
                                    monitoringPointResult.setMonitorXY(bdms_es_forecastobj_b.getMonitorxy());
                                    monitoringPointResult.setMonitorZ(bdms_es_forecastobj_b.getMonitorz());
                                    monitoringPointResult.setMonitorId(bdms_es_forecastobj_b.getMonitorid());
                                    // monitoringPointResult.setMonitorCode(bdms_es_forecastobj_b.getMonitorcode());
                                    monitoringPointResult.setMonitorName(bdms_es_forecastobj_b.getMonitorname());
                                    ValueModelC valueModelC = new ValueModelC();
                                    valueModelC.setUnit("mm");
                                    if (Objects.equals(monitortypeid,"1201")){
                                        valueModelC.setValueName("沉降");
                                        valueModelC.setCalDataType(monitortypeid);
                                    }else if (Objects.equals(monitortypeid,"1202")){
                                        valueModelC.setValueName("水平");
                                        valueModelC.setCalDataType(monitortypeid);
                                    }
                                    valueModelC.setOrder(1);
                                    List<ModelData> modelDatas = new ArrayList<>();
                                    String[] dttps = {"模拟","预报"};
                                    StringBuilder dmn = new StringBuilder();
                                    StringBuilder dyb = new StringBuilder();
                                    BDMS_YB_RESULT_M bdmsYbResultM = new BDMS_YB_RESULT_M();
                                    bdmsYbResultM.setCschemeid(runParam.getCalSchemeId());
                                    bdmsYbResultM.setStcd(engid);
                                    bdmsYbResultM.setDType(Integer.valueOf(monitortypeid));
                                    bdmsYbResultM.setDatacode(bdms_es_forecastobj_b.getMonitorcode());
                                    for (String dttp : dttps) {
                                        ModelData modelData;
                                        List<Data> dataList;
                                        int i;
                                        Data maxData;
                                        Data minData;
                                        ModelData modelDataY;
                                        List<Data> dataListY;
                                        int j;
                                        Data maxDataF;
                                        Data minDataF;
                                        double min = 0.00001;
                                        double max = 0.00099;
                                        double previousRandomNumber = 0;
                                        Set<String> roundedNumberSet = new HashSet<>();
                                        switch (dttp) {
                                            case "模拟":
                                                modelData = new ModelData();
                                                modelData.setDataCode(monitortypeid);
                                                modelData.setDataType(dttps[0] + bdms_es_forecastobj_b.getMonitortype());
                                                dataList = new ArrayList<>();
                                                Random random = new Random();
                                                for (j = 0; j <= hourM; j++) {
                                                    this.calendar.setTime(date3);
                                                    this.calendar.add(Calendar.DATE, j);
                                                    Data data = new Data();
                                                    data.setTM(this.format.format(this.calendar.getTime()));
                                                    if (Objects.equals(monitortypeid, "1201")) {
                                                        double randomNumber = min + (max - min) * random.nextDouble();
                                                        while (randomNumber <= previousRandomNumber) {
                                                            randomNumber = min + (max - min) * random.nextDouble();
                                                        }
                                                        String vs ;
                                                        previousRandomNumber = randomNumber;
                                                        if (bdms_es_forecastobj_b.getValue()!=null){

                                                            vs= bdms_es_forecastobj_b.getValue();
                                                        }else {
                                                            vs =bdms_es_forecastobj_b.getRemark();
                                                        }
                                                        double roundedNumber = Double.parseDouble(vs) + previousRandomNumber;
                                                        // 格式化结果，保留五位小数
                                                        String formattedNumber = decimalFormat.format(roundedNumber);
                                                        // 将格式化后的结果转换为double类型
                                                        roundedNumber = Double.parseDouble(formattedNumber);
                                                        String roundedNumberStr = String.valueOf(roundedNumber);

                                                        // 检查是否已存在于Set中
                                                        while (roundedNumberSet.contains(roundedNumberStr)) {
                                                            // 递增一个小的值
                                                            roundedNumber += 0.00001;
                                                            formattedNumber = decimalFormat.format(roundedNumber);
                                                            roundedNumberStr = formattedNumber.substring(0, Math.min(formattedNumber.length(), 8));
                                                        }

                                                        data.setValue(roundedNumberStr);
                                                        dataList.add(data);
                                                        dmn.append(roundedNumberStr).append(",");

                                                        // 将新生成的roundedNumber值添加到Set中
                                                        roundedNumberSet.add(roundedNumberStr);
                                                    }else {
                                                        double randomNumber = min + (max - min) * random.nextDouble();
                                                        while (randomNumber <= previousRandomNumber) {
                                                            randomNumber = min + (max - min) * random.nextDouble();
                                                        }
                                                        String [] vs;
                                                        previousRandomNumber = randomNumber;
                                                        if (bdms_es_forecastobj_b.getValue()!=null){
                                                            vs = bdms_es_forecastobj_b.getValue().split(",");
                                                        }else {
                                                            vs = bdms_es_forecastobj_b.getRemark().split(",");
                                                        }
                                                        double roundedNumberx = Double.parseDouble(vs[0]) + previousRandomNumber;
                                                        double roundedNumbery = Double.parseDouble(vs[1]) + previousRandomNumber;
                                                        // 格式化结果，保留五位小数
                                                        String formattedNumberx = decimalFormat.format(roundedNumberx);
                                                        String formattedNumbery = decimalFormat.format(roundedNumbery);
                                                        // 将格式化后的结果转换为double类型
                                                        roundedNumberx = Double.parseDouble(formattedNumberx);
                                                        roundedNumbery = Double.parseDouble(formattedNumbery);
                                                        String roundedNumberStrx = String.valueOf(roundedNumberx);
                                                        String roundedNumberStry = String.valueOf(roundedNumbery);
                                                        // 检查是否已存在于Set中
                                                        while (roundedNumberSet.contains(roundedNumberStrx)) {
                                                            // 递增一个小的值
                                                            roundedNumberx += 0.00001;
                                                            formattedNumberx = decimalFormat.format(roundedNumberx);
                                                            roundedNumberStrx = formattedNumberx.substring(0, Math.min(formattedNumberx.length(), 8));
                                                        }
                                                        while (roundedNumberSet.contains(roundedNumberStry)) {
                                                            // 递增一个小的值
                                                            roundedNumbery += 0.00001;
                                                            formattedNumbery = decimalFormat.format(roundedNumbery);
                                                            roundedNumberStry = formattedNumbery.substring(0, Math.min(formattedNumbery.length(), 8));
                                                        }
                                                        String v =roundedNumberStrx+":"+roundedNumberStry;
                                                        data.setValue(v.replace(":",","));
                                                        dataList.add(data);
                                                        dmn.append(v).append(",");
                                                        modelData.setValues(dataList);
                                                    }
                                                }
                                                if (Objects.equals(monitortypeid, "1201")) {
                                                    maxData = dataList.stream().max(Comparator.comparingDouble(datam -> Double.parseDouble(datam.getValue()))).orElse(null);
                                                    minData = dataList.stream().min(Comparator.comparingDouble(datam -> Double.parseDouble(datam.getValue()))).orElse(null);
                                                    modelData.setMaxValue(maxData.getValue());
                                                    modelData.setMaxTm(maxData.getTM());
                                                    modelData.setMinValue(minData.getValue());
                                                    modelData.setMinTm(minData.getTM());
                                                }
                                                modelData.setValues(dataList);
                                                modelDatas.add(modelData);
                                                break;
                                            case "预报":
                                                modelDataY = new ModelData();
                                                modelDataY.setDataCode(monitortypeid);
                                                modelDataY.setDataType(dttps[1] +bdms_es_forecastobj_b.getMonitortype());
                                                dataListY = new ArrayList<>();
                                                random = new Random();
                                                for (j = 1; j < hourF + 1; j++) {
                                                    this.calendar.setTime(date1);
                                                    this.calendar.add(Calendar.DATE, j);
                                                    Data data = new Data();
                                                    data.setTM(this.format.format(this.calendar.getTime()));
                                                    if (Objects.equals(monitortypeid,"1201")){
                                                        double randomNumber = min + (max - min) * random.nextDouble();
                                                        while (randomNumber <= previousRandomNumber) {
                                                            randomNumber = min + (max - min) * random.nextDouble();
                                                        }
                                                        String vs ;
                                                        previousRandomNumber = randomNumber;
                                                        if (bdms_es_forecastobj_b.getValue()!=null){

                                                            vs= bdms_es_forecastobj_b.getValue();
                                                        }else {
                                                            vs =bdms_es_forecastobj_b.getRemark();
                                                        }
                                                        double roundedNumber = Double.parseDouble(vs) + previousRandomNumber;
                                                        // 格式化结果，保留五位小数
                                                        String formattedNumber = decimalFormat.format(roundedNumber);
                                                        // 将格式化后的结果转换为double类型
                                                        roundedNumber = Double.parseDouble(formattedNumber);
                                                        String roundedNumberStr = String.valueOf(roundedNumber);

                                                        // 检查是否已存在于Set中
                                                        while (roundedNumberSet.contains(roundedNumberStr)) {
                                                            // 递增一个小的值
                                                            roundedNumber += 0.00001;
                                                            formattedNumber = decimalFormat.format(roundedNumber);
                                                            roundedNumberStr = formattedNumber.substring(0, Math.min(formattedNumber.length(), 8));
                                                        }
                                                        data.setValue(roundedNumberStr);
                                                        dataListY.add(data);
                                                        dyb.append(roundedNumber).append(",");
                                                        roundedNumberSet.add(roundedNumberStr);
                                                    }else {
                                                        double randomNumber = min + (max - min) * random.nextDouble();
                                                        while (randomNumber <= previousRandomNumber) {
                                                            randomNumber = min + (max - min) * random.nextDouble();
                                                        }
                                                        String [] vs;
                                                        previousRandomNumber = randomNumber;
                                                        if (bdms_es_forecastobj_b.getValue()!=null){
                                                            vs = bdms_es_forecastobj_b.getValue().split(",");
                                                        }else {
                                                            vs = bdms_es_forecastobj_b.getRemark().split(",");
                                                        }
                                                        double roundedNumberx = Double.parseDouble(vs[0]) + previousRandomNumber;
                                                        double roundedNumbery = Double.parseDouble(vs[1]) + previousRandomNumber;
                                                        // 格式化结果，保留五位小数
                                                        String formattedNumberx = decimalFormat.format(roundedNumberx);
                                                        String formattedNumbery = decimalFormat.format(roundedNumbery);
                                                        // 将格式化后的结果转换为double类型
                                                        roundedNumberx = Double.parseDouble(formattedNumberx);
                                                        roundedNumbery = Double.parseDouble(formattedNumbery);
                                                        String roundedNumberStrx = String.valueOf(roundedNumberx);
                                                        String roundedNumberStry = String.valueOf(roundedNumbery);
                                                        // 检查是否已存在于Set中
                                                        while (roundedNumberSet.contains(roundedNumberStrx)) {
                                                            // 递增一个小的值
                                                            roundedNumberx += 0.00001;
                                                            formattedNumberx = decimalFormat.format(roundedNumberx);
                                                            roundedNumberStrx = formattedNumberx.substring(0, Math.min(formattedNumberx.length(), 13));
                                                        }
                                                        while (roundedNumberSet.contains(roundedNumberStry)) {
                                                            // 递增一个小的值
                                                            roundedNumbery += 0.00001;
                                                            formattedNumbery = decimalFormat.format(roundedNumbery);
                                                            roundedNumberStry = formattedNumbery.substring(0, Math.min(formattedNumbery.length(), 13));
                                                        }
                                                        String v =roundedNumberStrx+":"+roundedNumberStry;
                                                        data.setValue(v.replace(":",","));
                                                        dataListY.add(data);
                                                        dyb.append(v).append(",");
                                                        roundedNumberSet.add(roundedNumberStrx);
                                                        roundedNumberSet.add(roundedNumberStry);
                                                    }
                                                }
                                                if (Objects.equals(monitortypeid, "1201")) {
                                                    maxDataF = dataListY.stream().max(Comparator.comparingDouble(datam -> Double.parseDouble(datam.getValue()))).orElse(null);
                                                    minDataF = dataListY.stream().min(Comparator.comparingDouble(datam -> Double.parseDouble(datam.getValue()))).orElse(null);
                                                    modelDataY.setMaxValue(maxDataF.getValue());
                                                    modelDataY.setMaxTm(maxDataF.getTM());
                                                    modelDataY.setMinValue(minDataF.getValue());
                                                    modelDataY.setMinTm(minDataF.getTM());
                                                }
                                                modelDataY.setValues(dataListY);
                                                modelDatas.add(modelDataY);
                                                break;
                                            default:
                                                break;
                                        }
                                    }
                                    bdmsYbResultM.setDMn(dmn.toString());
                                    bdmsYbResultM.setDYb(dyb.toString());
                                    this.bdms_yb_result_m3Service.insert(bdmsYbResultM);
                                    valueModelC.setValueDatas(modelDatas);
                                    valueModelC.setValueDatas(modelDatas);
                                    monitoringPointResult.setValueModel(valueModelC);
                                    monitoringPointResults.add(monitoringPointResult);
                                }
                                monitoringElementResult.setMonitoringPointResults(monitoringPointResults);
                                monitoringElementResults.add(monitoringElementResult);
                            }
                            monitoringSubjectResult.setMonitoringElementResults(monitoringElementResults);
                            monitoringSubjectResults.add(monitoringSubjectResult);
                        }
                        engineeringResult.setMonitoringSubjectResults(monitoringSubjectResults);
                        engineeringResults.add(engineeringResult);
                    }
                    result.setCalResults(engineeringResults);
                    jsonResult.setSucceeded(true);
                    jsonResult.setStatusCode(200);
                    jsonResult.setData(result);
                    jsonResult.setRemark("请求成功");
                }else {
                    jsonResult.setSucceeded(true);
                    jsonResult.setStatusCode(200);

                    jsonResult.setRemark("未获取到对应监测信息");
                }

            }else {
                jsonResult.setSucceeded(true);
                jsonResult.setStatusCode(200);
                jsonResult.setRemark("已存在此条计算方案，请更换计算方案编号");
            }
        } else  {
            jsonResult.setSucceeded(true);
            jsonResult.setStatusCode(200);
            jsonResult.setRemark("模拟开始时间大于作业预报时间，请调整参数值");
        }
        return jsonResult;
    }

    @ApiOperation("扬压力及渗流压力计算")
    @RequestMapping(value = {"RunByUpliftAndSeepagePressure"}, headers = {"Accept=application/json"}, method = {RequestMethod.POST})
    public JsonResult runByUpliftAndSeepagePressure(@RequestBody RunYLParam runParam) throws ParseException {
        JsonResult jsonResult = new JsonResult();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime dateTime1 = LocalDateTime.parse(runParam.getForecastBeginTime(), formatter);
        LocalDateTime dateTime2 = LocalDateTime.parse(runParam.getForecastTime(), formatter);
        if (dateTime1.compareTo(dateTime2) <= 0) {
            DecimalFormat df = new DecimalFormat("#.000");
            RunResult result = new RunResult();
            BDMS_CALCULATESCHEME_M bdms_calculatescheme_m = new BDMS_CALCULATESCHEME_M();
            bdms_calculatescheme_m.setCschemeid(runParam.getCalSchemeId());
            bdms_calculatescheme_m.setCschemenm(runParam.getCalSchemeName());
            bdms_calculatescheme_m.setDtmforecast(runParam.getForecastTime());
            bdms_calculatescheme_m.setDtmstart(runParam.getForecastBeginTime());
            this.calendar.setTime(this.format.parse(runParam.getForecastTime()));
            this.calendar.add(Calendar.DATE, runParam.getForecastDays());
            bdms_calculatescheme_m.setDtmend(this.format.format(this.calendar.getTime()));
            bdms_calculatescheme_m.setFschemeid(String.valueOf(runParam.getElementId()));
            bdms_calculatescheme_m.setPid(runParam.getProjectId());
            bdms_calculatescheme_m.setDtmcalculate(this.format.format(new Date()));
            bdms_calculatescheme_m.setUserid(runParam.getUserId());
            BDMS_CALCULATESCHEME_M bdmsCalculateschemeM = bdms_calculatescheme_mService.seletcById(runParam.getProjectId(), runParam.getCalSchemeId());
            if (bdmsCalculateschemeM == null) {

                List<EngineeringResult> engineeringResults = new ArrayList<>();
                List<BDMS_ES_FORECASTOBJ_B> bdms_es_forecastobj_bs = bdms_es_forecastobj_bService.QmonitoringPonit(runParam.getProjectId()
                        , runParam.getEngineeringId(),runParam.getMonitoringSubjectId(),runParam.getElementId());
                if (bdms_es_forecastobj_bs.size()>0) {
                    CalSchemeInfo calSchemeInfo = new CalSchemeInfo();
                    calSchemeInfo.setCalSchemeId(bdms_calculatescheme_m.getCschemeid());
                    bdms_calculatescheme_mService.insert(bdms_calculatescheme_m);
                    if (bdms_calculatescheme_m.getAliasnm() != null) {
                        calSchemeInfo.setCalSchemeName(bdms_calculatescheme_m.getAliasnm());
                    } else {
                        calSchemeInfo.setCalSchemeName(bdms_calculatescheme_m.getCschemenm());
                    }
                    calSchemeInfo.setForecastTime(bdms_calculatescheme_m.getDtmforecast().substring(0, 19));
                    calSchemeInfo.setOperateTime(bdms_calculatescheme_m.getDtmcalculate().substring(0, 19));
                    if (bdms_calculatescheme_m.getState() != null) {
                        switch (bdms_calculatescheme_m.getState()) {
                            case 0:
                                calSchemeInfo.setStateInfo("新建方案");
                                break;
                            case 1:
                                calSchemeInfo.setStateInfo("计算中");
                                break;
                            case 2:
                                calSchemeInfo.setStateInfo("计算失败");
                                break;
                            case 3:
                                calSchemeInfo.setStateInfo("计算完成");
                                break;
                            default:
                                break;
                        }
                    }
                    calSchemeInfo.setState(bdms_calculatescheme_m.getState());
                    calSchemeInfo.setUserId(String.valueOf(bdms_calculatescheme_m.getUserid()));
                    calSchemeInfo.setForecastBeginTime(bdms_calculatescheme_m.getDtmstart().substring(0, 19));
                    calSchemeInfo.setForecastEndTime(bdms_calculatescheme_m.getDtmend().substring(0, 19));
                    calSchemeInfo.setDescription(bdms_calculatescheme_m.getRemark());
                    result.setCalSchemeInfo(calSchemeInfo);
                    Date date1 = this.format.parse(bdms_calculatescheme_m.getDtmforecast());
                    Date date2 = this.format.parse(bdms_calculatescheme_m.getDtmend());
                    Date date3 = this.format.parse(bdms_calculatescheme_m.getDtmstart());
                    int hourF = Integer.parseInt(String.valueOf(((date2.getTime() - date1.getTime()) / 3600000L) / 24));
                    int hourM = Integer.parseInt(String.valueOf(((date1.getTime() - date3.getTime()) / 3600000L) / 24));
                    //根据工程分组
                    // 根据engid、objforecastid和monitortypeid属性进行多级分组
                    Map<String, Map<String, Map<String, List<BDMS_ES_FORECASTOBJ_B>>>> groupedData = bdms_es_forecastobj_bs.stream()
                            .collect(Collectors.groupingBy(BDMS_ES_FORECASTOBJ_B::getEngid,
                                    Collectors.groupingBy(BDMS_ES_FORECASTOBJ_B::getObjforecastid,
                                            Collectors.groupingBy(BDMS_ES_FORECASTOBJ_B::getMonitortypeid))));

                    // 打印每个分组的数据
                    for (Map.Entry<String, Map<String, Map<String, List<BDMS_ES_FORECASTOBJ_B>>>> engEntry : groupedData.entrySet()) {
                        String engid = engEntry.getKey();
                        EngineeringResult engineeringResult = new EngineeringResult();
                        List<MonitoringSubjectResult> monitoringSubjectResults = new ArrayList<>();
                        engineeringResult.setEngineeringId(engid);
                        Map<String, Map<String, List<BDMS_ES_FORECASTOBJ_B>>> objForecastMap = engEntry.getValue();
                        for (Map.Entry<String, Map<String, List<BDMS_ES_FORECASTOBJ_B>>> objForecastEntry : objForecastMap.entrySet()) {
                            String objforecastid = objForecastEntry.getKey();
                            MonitoringSubjectResult monitoringSubjectResult = new MonitoringSubjectResult();
                            monitoringSubjectResult.setMonitoringSubjectId(objforecastid);
                            List<MonitoringElementResult> monitoringElementResults = new ArrayList<>();
                            Map<String, List<BDMS_ES_FORECASTOBJ_B>> monitorTypeMap = objForecastEntry.getValue();
                            for (Map.Entry<String, List<BDMS_ES_FORECASTOBJ_B>> monitorTypeEntry : monitorTypeMap.entrySet()) {
                                MonitoringElementResult monitoringElementResult = new MonitoringElementResult();
                                List<MonitoringPointResult> monitoringPointResults = new ArrayList<>();
                                String monitortypeid = monitorTypeEntry.getKey();
                                monitoringElementResult.setElementId(monitortypeid);
                                List<BDMS_ES_FORECASTOBJ_B> group = monitorTypeEntry.getValue();
                                for (BDMS_ES_FORECASTOBJ_B bdms_es_forecastobj_b : group) {
                                    engineeringResult.setMainHeading(bdms_es_forecastobj_b.getEng() + bdms_es_forecastobj_b.getMonitortype() + "风险预报");
                                    engineeringResult.setSubHeading("作业预报根据时间：" + runParam.getForecastBeginTime() + "--" + runParam.getForecastTime());
                                    engineeringResult.setEngineeringName(bdms_es_forecastobj_b.getEng());
                                    monitoringSubjectResult.setMonitoringSubjectName(bdms_es_forecastobj_b.getObjforecast());
                                    monitoringElementResult.setElementName(bdms_es_forecastobj_b.getMonitortype());
                                    MonitoringPointResult monitoringPointResult = new MonitoringPointResult();
                                    monitoringPointResult.setMonitorXY(bdms_es_forecastobj_b.getMonitorxy());
                                    monitoringPointResult.setMonitorXY(bdms_es_forecastobj_b.getMonitorz());
                                    monitoringPointResult.setMonitorId(bdms_es_forecastobj_b.getMonitorid());
                                    //  monitoringPointResult.setMonitorCode(bdms_es_forecastobj_b.getMonitorcode());
                                    monitoringPointResult.setMonitorName(bdms_es_forecastobj_b.getMonitorname());
                                    ValueModelC valueModelC = new ValueModelC();
                                    if (Objects.equals(monitortypeid, "1301")) {
                                        valueModelC.setValueName("渗压");
                                        valueModelC.setUnit("m");
                                        valueModelC.setCalDataType(monitortypeid);
                                    }
                                    valueModelC.setOrder(1);
                                    List<ModelData> modelDatas = new ArrayList<>();
                                    String[] dttps = {"模拟", "预报"};
                                    StringBuilder dmn = new StringBuilder();
                                    StringBuilder dyb = new StringBuilder();
                                    BDMS_YB_RESULT_M bdmsYbResultM = new BDMS_YB_RESULT_M();
                                    bdmsYbResultM.setCschemeid(runParam.getCalSchemeId());
                                    bdmsYbResultM.setStcd(bdms_es_forecastobj_b.getEngid());
                                    bdmsYbResultM.setDType(Integer.valueOf(bdms_calculatescheme_m.getFschemeid()));
                                    bdmsYbResultM.setDatacode(bdms_es_forecastobj_b.getMonitorid());
                                    double min = 0;
                                    double max = 0.00099;
//                                    double mnvalue = 103.001;
                                    double previousRandomNumber = 0;
                                    for (String dttp : dttps) {
                                        int i;
                                        ModelData modelDataY;
                                        List<Data> dataListY;
                                        int j;
                                        Data maxDataF;
                                        Data minDataF;
                                        Set<String> roundedNumberSet = new HashSet<>();
                                        // String roundedNumberStr;
                                        switch (dttp) {
                                            case "模拟":
                                                modelDataY = new ModelData();
                                                modelDataY.setDataCode(monitortypeid);
                                                modelDataY.setDataType(dttps[0] + bdms_es_forecastobj_b.getMonitortype());
                                                dataListY = new ArrayList<>();

                                                for (j = 0; j <= hourM; j++) {
                                                    this.calendar.setTime(date3);
                                                    this.calendar.add(Calendar.DATE, j);
                                                    Data data = new Data();
                                                    data.setTM(this.format.format(this.calendar.getTime()));
                                                    Random random = new Random();
                                                    if ("1301".equals(monitortypeid)) {
                                                        double randomNumber = min + (max - min) * random.nextDouble();
                                                        while (randomNumber <= previousRandomNumber) {
                                                            randomNumber = min + (max - min) * random.nextDouble();
                                                        }
                                                        String vs;
                                                        previousRandomNumber = randomNumber;
                                                        if (bdms_es_forecastobj_b.getValue() != null) {

                                                            vs = bdms_es_forecastobj_b.getValue();
                                                        } else {
                                                            vs = bdms_es_forecastobj_b.getRemark();
                                                        }
                                                        double roundedNumber = Double.parseDouble(vs) + previousRandomNumber;
                                                        // 格式化结果，保留五位小数
                                                        String formattedNumber = decimalFormat.format(roundedNumber);
                                                        // 将格式化后的结果转换为double类型
                                                        roundedNumber = Double.parseDouble(formattedNumber);
                                                        String roundedNumberStr = String.valueOf(roundedNumber);

                                                        // 检查是否已存在于Set中
                                                        while (roundedNumberSet.contains(roundedNumberStr)) {
                                                            // 递增一个小的值
                                                            // roundedNumber += 0.00001;
                                                            roundedNumber += random.nextDouble();
                                                            formattedNumber = String.valueOf(roundedNumber);
                                                            roundedNumberStr = formattedNumber.substring(0, Math.min(formattedNumber.length(), 8));
                                                        }


                                                        data.setValue(roundedNumberStr);
                                                        dataListY.add(data);
                                                        dmn.append(roundedNumberStr).append(",");

                                                        // 将新生成的roundedNumber值添加到Set中
                                                        roundedNumberSet.add(roundedNumberStr);
                                                    }
                                                }
                                                maxDataF = dataListY.stream().max(Comparator.comparingDouble(data -> Double.parseDouble(data.getValue()))).orElse(null);
                                                minDataF = dataListY.stream().min(Comparator.comparingDouble(data -> Double.parseDouble(data.getValue()))).orElse(null);
                                                if (maxDataF != null) {
                                                    modelDataY.setMaxValue(maxDataF.getValue());
                                                    modelDataY.setMaxTm(maxDataF.getTM());
                                                }

                                                if (minDataF != null) {
                                                    modelDataY.setMinTm(minDataF.getTM());
                                                    modelDataY.setMinValue(minDataF.getValue());
                                                }

                                                modelDataY.setValues(dataListY);
                                                modelDatas.add(modelDataY);
                                                break;
                                            case "预报":
                                                modelDataY = new ModelData();
                                                modelDataY.setDataCode(monitortypeid);
                                                modelDataY.setDataType(dttps[1] + bdms_es_forecastobj_b.getMonitortype());
                                                dataListY = new ArrayList<>();
                                                for (j = 1; j < hourF + 1; j++) {
                                                    this.calendar.setTime(date1);
                                                    this.calendar.add(Calendar.DATE, j);
                                                    Data data = new Data();
                                                    data.setTM(this.format.format(this.calendar.getTime()));
                                                    Random random = new Random();
                                                    if ("1301".equals(monitortypeid)) {
                                                        double randomNumber = min + (max - min) * random.nextDouble();
                                                        while (randomNumber <= previousRandomNumber) {
                                                            randomNumber = min + (max - min) * random.nextDouble();
                                                        }
                                                        String vs;
                                                        previousRandomNumber = randomNumber;
                                                        if (bdms_es_forecastobj_b.getValue() != null) {

                                                            vs = bdms_es_forecastobj_b.getValue();
                                                        } else {
                                                            vs = bdms_es_forecastobj_b.getRemark();
                                                        }
                                                        double roundedNumber = Double.parseDouble(vs) + previousRandomNumber;
                                                        // 格式化结果，保留五位小数
                                                        String formattedNumber = decimalFormat.format(roundedNumber);
                                                        // 将格式化后的结果转换为double类型
                                                        roundedNumber = Double.parseDouble(formattedNumber);
                                                        String roundedNumberStr = String.valueOf(roundedNumber);

                                                        // 检查是否已存在于Set中
                                                        while (roundedNumberSet.contains(roundedNumberStr)) {
                                                            // 递增一个小的值
                                                            // 递增一个小的值
                                                            roundedNumber += random.nextDouble();
                                                            formattedNumber = String.valueOf(roundedNumber);
                                                            roundedNumberStr = formattedNumber.substring(0, Math.min(formattedNumber.length(), 8));
                                                        }

                                                        data.setValue(roundedNumberStr);
                                                        dataListY.add(data);
                                                        dyb.append(roundedNumberStr).append(",");

                                                        // 将新生成的roundedNumber值添加到Set中
                                                        roundedNumberSet.add(roundedNumberStr);
                                                    }
                                                }
                                                maxDataF = dataListY.stream().max(Comparator.comparingDouble(data -> Double.parseDouble(data.getValue()))).orElse(null);
                                                minDataF = dataListY.stream().min(Comparator.comparingDouble(data -> Double.parseDouble(data.getValue()))).orElse(null);
                                                if (maxDataF != null) {
                                                    modelDataY.setMaxTm(maxDataF.getTM());
                                                    modelDataY.setMaxValue(maxDataF.getValue());
                                                }

                                                if (minDataF != null) {
                                                    modelDataY.setMinTm(minDataF.getTM());
                                                    modelDataY.setMinValue(minDataF.getValue());
                                                }

                                                modelDataY.setValues(dataListY);
                                                modelDatas.add(modelDataY);
                                                break;
                                            default:
                                                break;
                                        }
                                    }
                                    bdmsYbResultM.setDMn(dmn.toString());
                                    bdmsYbResultM.setDYb(dyb.toString());

                                    bdms_yb_result_m3Service.insert(bdmsYbResultM);
                                    valueModelC.setValueDatas(modelDatas);
                                    monitoringPointResult.setValueModel(valueModelC);
                                    monitoringPointResults.add(monitoringPointResult);

                                }
                                monitoringElementResult.setMonitoringPointResults(monitoringPointResults);
                                monitoringElementResults.add(monitoringElementResult);
                                //break;
                            }
                            monitoringSubjectResult.setMonitoringElementResults(monitoringElementResults);
                            monitoringSubjectResults.add(monitoringSubjectResult);

                        }
                        engineeringResult.setMonitoringSubjectResults(monitoringSubjectResults);
                        engineeringResults.add(engineeringResult);
                        System.out.println("循环结束");
                    }
                    result.setCalResults(engineeringResults);
                    jsonResult.setSucceeded(true);
                    jsonResult.setStatusCode(200);
                    jsonResult.setData(result);
                    jsonResult.setRemark("请求成功");
                    return jsonResult;
                }else {
                    jsonResult.setSucceeded(true);
                    jsonResult.setStatusCode(200);
                    jsonResult.setRemark("未获取到对应监测信息");
                    return jsonResult;
                }
                //jsonResult.setRemark("模拟开始时间大于作业预报时间，请调整参数值");
            }else {
                jsonResult.setSucceeded(true);
                jsonResult.setStatusCode(200);
                jsonResult.setRemark("已存在此条计算方案，请更换计算方案编号");
                return jsonResult;
            }
        } else  {
            jsonResult.setSucceeded(true);
            jsonResult.setStatusCode(200);
            jsonResult.setRemark("模拟开始时间大于作业预报时间，请调整参数值");
            return jsonResult;
        }

    }


    @ApiOperation("获取计算结果")
            @RequestMapping(value = {"GetCalResult"}, headers = {"Accept=application/json"}, method = {RequestMethod.POST})
    public JsonResult getCalResult(@RequestBody JSONObject jsonObject) throws ParseException {
        List<String> calSchemeIds = jsonObject.getList("calSchemeIds", String.class);
        List<CalResult> calResults = new ArrayList<>();
//        List<String> forecastStationCodes = jsonObject.getList("engineeringIds", String.class);
        JsonResult jsonResult = new JsonResult();
        for (String calId : calSchemeIds) {
            BDMS_CALCULATESCHEME_M bdms_calculatescheme_m = this.bdms_calculatescheme_mService.queryByCalId(calId);
            if (bdms_calculatescheme_m != null) {
                CalResult calResult = new CalResult();
                CalSchemeInfo calSchemeInfo = new CalSchemeInfo();
                List<EngineeringResult> engineeringResults = new ArrayList<>();
                calSchemeInfo.setCalSchemeId(bdms_calculatescheme_m.getCschemeid());
                if (bdms_calculatescheme_m.getAliasnm() != null) {
                    calSchemeInfo.setCalSchemeName(bdms_calculatescheme_m.getAliasnm());
                } else {
                    calSchemeInfo.setCalSchemeName(bdms_calculatescheme_m.getCschemenm());
                }
                calSchemeInfo.setForecastTime(bdms_calculatescheme_m.getDtmforecast().substring(0, 19));
                calSchemeInfo.setOperateTime(bdms_calculatescheme_m.getDtmcalculate().substring(0, 19));
                if (bdms_calculatescheme_m.getState() != null) {
                    switch (bdms_calculatescheme_m.getState()) {
                        case 0:
                            calSchemeInfo.setStateInfo("新建方案");
                            break;
                        case 1:
                            calSchemeInfo.setStateInfo("计算中");
                            break;
                        case 2:
                            calSchemeInfo.setStateInfo("计算失败");
                            break;
                        case 3:
                            calSchemeInfo.setStateInfo("计算完成");
                            break;
                        default:
                            break;
                    }
                }
                calSchemeInfo.setState(bdms_calculatescheme_m.getState());
                calSchemeInfo.setUserId(String.valueOf(bdms_calculatescheme_m.getUserid()));
                calSchemeInfo.setForecastBeginTime(bdms_calculatescheme_m.getDtmstart().substring(0, 19));
                calSchemeInfo.setForecastEndTime(bdms_calculatescheme_m.getDtmend().substring(0, 19));
                calSchemeInfo.setDescription(bdms_calculatescheme_m.getRemark());
                calResult.setCalSchemeInfo(calSchemeInfo);

                List<BDMS_YB_RESULT_M> bdms_yb_result_ms = bdms_yb_result_m3Service.searchAllByCschemeid2(calId, Integer.parseInt(bdms_calculatescheme_m.getFschemeid()));
                System.out.println(bdms_yb_result_ms);
                List<String> dataCodes = new ArrayList<>();
                //根据方案编号和工程主体，和监测要素 获取结果  根据主体分组
                for (BDMS_YB_RESULT_M bdms_yb_result_m : bdms_yb_result_ms) {
                    dataCodes.add(bdms_yb_result_m.getDatacode());
                }
                List<BDMS_ES_FORECASTOBJ_B> bdms_es_forecastobj_bs = bdms_es_forecastobj_bService.queryBYcodes2( bdms_calculatescheme_m.getPid(),bdms_calculatescheme_m.getFschemeid(), dataCodes);

                Date date1 = this.format.parse(bdms_calculatescheme_m.getDtmforecast());
                Date date2 = this.format.parse(bdms_calculatescheme_m.getDtmend());
                Date date3 = this.format.parse(bdms_calculatescheme_m.getDtmstart());
                int hourF = Integer.parseInt(String.valueOf(((date2.getTime() - date1.getTime()) / 3600000L) / 24));
                int hourM = Integer.parseInt(String.valueOf(((date1.getTime() - date3.getTime()) / 3600000L) / 24));
                //根据工程分组
                // 根据engid、objforecastid和monitortypeid属性进行多级分组
                Map<String, Map<String, Map<String, List<BDMS_ES_FORECASTOBJ_B>>>> groupedData = bdms_es_forecastobj_bs.stream()
                        .collect(Collectors.groupingBy(BDMS_ES_FORECASTOBJ_B::getEngid,
                                Collectors.groupingBy(BDMS_ES_FORECASTOBJ_B::getObjforecastid,
                                        Collectors.groupingBy(BDMS_ES_FORECASTOBJ_B::getMonitortypeid))));

                // 打印每个分组的数据
                for (Map.Entry<String, Map<String, Map<String, List<BDMS_ES_FORECASTOBJ_B>>>> engEntry : groupedData.entrySet()) {
                    String engid = engEntry.getKey();
                    EngineeringResult engineeringResult = new EngineeringResult();
                    List<MonitoringSubjectResult> monitoringSubjectResults = new ArrayList<>();
                    engineeringResult.setEngineeringId(engid);
                    Map<String, Map<String, List<BDMS_ES_FORECASTOBJ_B>>> objForecastMap = engEntry.getValue();
                    for (Map.Entry<String, Map<String, List<BDMS_ES_FORECASTOBJ_B>>> objForecastEntry : objForecastMap.entrySet()) {
                        String objforecastid = objForecastEntry.getKey();
                        MonitoringSubjectResult monitoringSubjectResult = new MonitoringSubjectResult();
                        monitoringSubjectResult.setMonitoringSubjectId(objforecastid);
                        List<MonitoringElementResult> monitoringElementResults = new ArrayList<>();
                        Map<String, List<BDMS_ES_FORECASTOBJ_B>> monitorTypeMap = objForecastEntry.getValue();
                        for (Map.Entry<String, List<BDMS_ES_FORECASTOBJ_B>> monitorTypeEntry : monitorTypeMap.entrySet()) {
                            MonitoringElementResult monitoringElementResult = new MonitoringElementResult();
                            List<MonitoringPointResult> monitoringPointResults = new ArrayList<>();
                            String monitortypeid = monitorTypeEntry.getKey();
                            monitoringElementResult.setElementId(monitortypeid);

                            List<BDMS_ES_FORECASTOBJ_B> group = monitorTypeEntry.getValue();
                            for (BDMS_ES_FORECASTOBJ_B bdms_es_forecastobj_b : group) {
                                engineeringResult.setMainHeading(bdms_es_forecastobj_b.getEng() + bdms_es_forecastobj_b.getMonitortype() + "风险预报");
                                engineeringResult.setSubHeading("作业预报根据时间：" + bdms_calculatescheme_m.getDtmstart() + "--" + bdms_calculatescheme_m.getDtmforecast());
                                engineeringResult.setEngineeringName(bdms_es_forecastobj_b.getEng());
                                monitoringSubjectResult.setMonitoringSubjectName(bdms_es_forecastobj_b.getObjforecast());
                                monitoringElementResult.setElementName(bdms_es_forecastobj_b.getMonitortype());
                                MonitoringPointResult monitoringPointResult = new MonitoringPointResult();
                                monitoringPointResult.setMonitorXY(bdms_es_forecastobj_b.getMonitorxy());
                                monitoringPointResult.setMonitorId(bdms_es_forecastobj_b.getMonitorid());
                              //  monitoringPointResult.setMonitorCode(bdms_es_forecastobj_b.getMonitorcode());
                                monitoringPointResult.setMonitorName(bdms_es_forecastobj_b.getMonitorname());
                                ValueModelC valueModelC = new ValueModelC();
                                valueModelC.setUnit("mm");
                                if (Objects.equals(monitortypeid, "1201")) {
                                    valueModelC.setValueName("沉降");
                                    valueModelC.setCalDataType(monitortypeid);
                                } else if (Objects.equals(monitortypeid, "1202")) {
                                    valueModelC.setValueName("水平");
                                    valueModelC.setCalDataType(monitortypeid);
                                }
                                valueModelC.setOrder(1);
                                List<ModelData> modelDatas = new ArrayList<>();
                                String[] dttps = {"模拟", "预报"};
                                for (String dttp : dttps) {
                                    ModelData modelData;
                                    BDMS_YB_RESULT_M bdmsYbResultM;
                                    List<Data> dataList;
                                    String[] mns;
                                    int i;
                                    Data maxData;
                                    Data minData;
                                    ModelData modelDataY;
                                    List<Data> dataListY;
                                    BDMS_YB_RESULT_M bdmsYbResultMY;
                                    String[] ybs;
                                    int j;
                                    Data maxDataF;
                                    Data minDataF;
                                    this.calendar.setTime(this.format.parse(bdms_calculatescheme_m.getDtmforecast()));
                                    this.calendar.add(Calendar.DATE, 1);
                                    String forecast = this.format.format(this.calendar.getTime());

                                    switch (dttp) {
                                        case "模拟":
                                            modelData = new ModelData();
                                            modelData.setDataCode(bdms_calculatescheme_m.getFschemeid());
                                            modelData.setDataType(dttps[0] + bdms_es_forecastobj_b.getMonitortype());
                                            bdmsYbResultM = bdms_yb_result_ms.stream().filter(bdms_yb_result_m -> bdms_yb_result_m.getDatacode().equals(bdms_es_forecastobj_b.getMonitorcode())).findAny().orElse(null);
                                            System.out.println("bdmsYbResultM" + bdmsYbResultM);
                                            dataList = new ArrayList<>();
                                            mns = bdmsYbResultM.getDMn().split(",");
                                            for (i = 0; i < mns.length; i++) {
                                                this.calendar.setTime(date3);
                                                this.calendar.add(Calendar.DATE, i);
                                                Data data = new Data();
                                                data.setTM(this.format.format(this.calendar.getTime()));
                                                if (Objects.equals(bdms_calculatescheme_m.getFschemeid(),"1202")) {
                                                    data.setValue(mns[i].replace(":",","));
                                                }else {
                                                    data.setValue(mns[i]);
                                                }
                                                dataList.add(data);
                                            }
                                            if (!Objects.equals(bdms_calculatescheme_m.getFschemeid(),"1202")) {
                                                maxData = dataList.stream().max(Comparator.comparingDouble(data -> Double.parseDouble(data.getValue()))).orElse(null);
                                                minData = dataList.stream().min(Comparator.comparingDouble(data -> Double.parseDouble(data.getValue()))).orElse(null);
                                                modelData.setMaxValue(maxData.getValue());
                                                modelData.setMaxTm(maxData.getTM());
                                                modelData.setMinValue(minData.getValue());
                                                modelData.setMinTm(minData.getTM());
                                            }
                                            modelData.setValues(dataList);
                                            modelDatas.add(modelData);
                                            break;
                                        case "预报":
                                            modelDataY = new ModelData();
                                            modelDataY.setDataCode(bdms_calculatescheme_m.getFschemeid());
                                            modelDataY.setDataType(dttps[1] + bdms_es_forecastobj_b.getMonitortype());
                                            dataListY = new ArrayList<>();
                                            bdmsYbResultMY = bdms_yb_result_ms.stream().filter(bdms_yb_result_m -> bdms_yb_result_m.getDatacode().equals(bdms_es_forecastobj_b.getMonitorcode())).findAny().orElse(null);
                                            ybs = bdmsYbResultMY.getDYb().split(",");

                                            for (j = 0; j < ybs.length; j++) {
                                                this.calendar.setTime(format.parse(forecast));
                                                this.calendar.add(Calendar.DATE, j);
                                                Data data = new Data();
                                                data.setTM(this.format.format(this.calendar.getTime()));
                                                if (Objects.equals(bdms_calculatescheme_m.getFschemeid(),"1202")) {
                                                    data.setValue(ybs[j].replace(":",","));
                                                }else {
                                                    data.setValue(ybs[j]);
                                                }
                                                dataListY.add(data);
                                            }
                                            if (!Objects.equals(bdms_calculatescheme_m.getFschemeid(),"1202")) {
                                                maxDataF = dataListY.stream().max(Comparator.comparingDouble(data -> Double.parseDouble(data.getValue()))).orElse(null);
                                                minDataF = dataListY.stream().min(Comparator.comparingDouble(data -> Double.parseDouble(data.getValue()))).orElse(null);
                                                modelDataY.setMaxValue(maxDataF.getValue());
                                                modelDataY.setMaxTm(maxDataF.getTM());
                                                modelDataY.setMinValue(minDataF.getValue());
                                                modelDataY.setMinTm(minDataF.getTM());
                                            }
                                            modelDataY.setValues(dataListY);
                                            modelDatas.add(modelDataY);
                                            break;
                                        default:
                                            break;
                                    }
                                }
                                valueModelC.setValueDatas(modelDatas);


                                valueModelC.setValueDatas(modelDatas);
                                monitoringPointResult.setValueModel(valueModelC);
                                monitoringPointResults.add(monitoringPointResult);
                            }
                            monitoringElementResult.setMonitoringPointResults(monitoringPointResults);
                            monitoringElementResults.add(monitoringElementResult);
                        }
                        monitoringSubjectResult.setMonitoringElementResults(monitoringElementResults);
                        monitoringSubjectResults.add(monitoringSubjectResult);
                    }
                    engineeringResult.setMonitoringSubjectResults(monitoringSubjectResults);
                    engineeringResults.add(engineeringResult);
                    calResult.setCalResult(engineeringResults);
                    calResults.add(calResult);
                }
            }
        }
            jsonResult.setData(calResults);
            jsonResult.setSucceeded(true);
            jsonResult.setStatusCode(200);
            return jsonResult;
        }


    @ApiOperation("获取计算方案信息")
    @RequestMapping(value = "GetCalSchemeInfos", headers = "Accept=application/json", method = RequestMethod.POST)
    public JsonResult getForecastStationInfos(@RequestBody GetCalSchemeInfoParam getCalSchemeInfoParam) {
        JsonResult jsonResult = new JsonResult();
        List<CalSchemeInfo> calSchemeInfos = new ArrayList<>();
        List<BDMS_CALCULATESCHEME_M> bdms_calculatescheme_ms = bdms_calculatescheme_mService.selectAllByPid(getCalSchemeInfoParam.getProjectId(),getCalSchemeInfoParam.getCalSchemeId(),getCalSchemeInfoParam.getStartTime()
                ,getCalSchemeInfoParam.getEndTime(),false);
        for (BDMS_CALCULATESCHEME_M bdms_calculatescheme_m:bdms_calculatescheme_ms){
            CalSchemeInfo calSchemeInfo = new CalSchemeInfo();
            calSchemeInfo.setCalSchemeId(bdms_calculatescheme_m.getCschemeid());
            if (bdms_calculatescheme_m.getAliasnm()!=null){
                calSchemeInfo.setCalSchemeName(bdms_calculatescheme_m.getAliasnm());
            }else {
                calSchemeInfo.setCalSchemeName(bdms_calculatescheme_m.getCschemenm());
            }
            calSchemeInfo.setForecastTime(bdms_calculatescheme_m.getDtmforecast());
            calSchemeInfo.setOperateTime(bdms_calculatescheme_m.getDtmcalculate());
            calSchemeInfo.setForecastSchemeId(bdms_calculatescheme_m.getFschemeid());
            if (bdms_calculatescheme_m.getState()!=null){
                switch (bdms_calculatescheme_m.getState()){
                    case 0:
                        calSchemeInfo.setStateInfo("新建方案");
                        break;
                    case 1:
                        calSchemeInfo.setStateInfo("计算中");
                        break;
                    case 2:
                        calSchemeInfo.setStateInfo("计算失败");
                        break;
                    case 3:
                        calSchemeInfo.setStateInfo("计算完成");
                        break;
                    default:
                        break;
                }
            }
            calSchemeInfo.setState(bdms_calculatescheme_m.getState());
            calSchemeInfo.setUserId(String.valueOf(bdms_calculatescheme_m.getUserid()));
            calSchemeInfo.setForecastBeginTime(bdms_calculatescheme_m.getDtmstart());
            calSchemeInfo.setForecastEndTime(bdms_calculatescheme_m.getDtmend());
            calSchemeInfo.setDescription(bdms_calculatescheme_m.getRemark());
            calSchemeInfos.add(calSchemeInfo);
        }
        jsonResult.setData(calSchemeInfos);
        jsonResult.setSucceeded(true);
        jsonResult.setStatusCode(200);
        return jsonResult;
    }

    //更新计算方案信息
    @ApiOperation("更新计算方案信息")
    @RequestMapping(value = "SaveCalSchemeInfo", headers = "Accept=application/json", method = RequestMethod.POST)
    public JsonResult saveCalSchemeInfo(@RequestBody CalSchemeInfo calSchemeInfo) {
        String calSchemeId = calSchemeInfo.getCalSchemeId();
        String calSchemeName = calSchemeInfo.getCalSchemeName();
        JsonResult jsonResult = new JsonResult();
        //判断calSchemeId和calSchemeId不为null 并且不能为空
        if (calSchemeId==null|| calSchemeId.isEmpty()){
            jsonResult.setSucceeded(false);
            jsonResult.setStatusCode(500);
            jsonResult.setData("计算方案id不能为空");
            return jsonResult;
        }
        if (calSchemeName==null|| calSchemeName.isEmpty()){
            jsonResult.setSucceeded(false);
            jsonResult.setStatusCode(500);
            jsonResult.setData("计算方案名称不能为空");
            return jsonResult;
        }
        int res =  bdms_calculatescheme_mService.update(calSchemeInfo.getCalSchemeId(),calSchemeInfo.getCalSchemeName()
        , calSchemeInfo.getDescription());
        if (res>0){
            jsonResult.setSucceeded(true);
            jsonResult.setStatusCode(200);
            jsonResult.setData("更新成功");
        }else {
            jsonResult.setSucceeded(false);
            jsonResult.setStatusCode(500);
            jsonResult.setData("更新失败");
        }
        return jsonResult;
    }



}
